/*
 * Copyright 2015 William Wang.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package wxk.Bonus.FXML;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import wxk.Bonus.Analyst.UnionLottoBI;
import wxk.Bonus.Constant.DBContant;
import wxk.Bonus.Constant.GlobalConfig;
import wxk.Bonus.Network.UnionLottoSync;
import wxk.Bonus.bean.ChinaDoubleBallBean;
import wxk.Bonus.utils.BonusLogger;
import wxk.Bonus.utils.MessageUtils;
import wxk.Bonus.utils.ScreenUtil;
import wxk.Bonus.utils.Toolkit;

/**
 * FXML Controller class
 *
 * @author William Wang
 */
public class DoubleBallController implements Initializable {
     static GlobalConfig globalconfig=GlobalConfig.getInstance();
    
    @FXML private GridPane maingridpane;
    @FXML private TableView<ChinaDoubleBallBean> tableView;
    @FXML private HBox content_region;
    @FXML private HBox new_record_region;
    @FXML private Label uniontitlelabel;
    @FXML private TextField filterField,blueballfilterField,redballfilterField;
    @FXML private Slider ftermsld,ntermsld;
    @FXML private TextField ftermnum,ntermnum;
    @FXML CheckBox foptional,noptional;
    
    URL location;
     FXMLLoader fxmlLoader;
      SortedList<ChinaDoubleBallBean> sortedData;

    
    public GridPane getMaingridpane() {
        return maingridpane;
    }

    public HBox getContent_region() {
        return content_region;
    }

    public HBox getNew_record_region() {
        return new_record_region;
    }
    
    public TableView<ChinaDoubleBallBean> getTableView() {
        return tableView;
    }
    
    @FXML private TextField termField;
    @FXML private TextField dateField;
    @FXML private TextField red1Field;
    @FXML private TextField red2Field;
    @FXML private TextField red3Field;
    @FXML private TextField red4Field;
    @FXML private TextField red5Field;
    @FXML private TextField red6Field;
    @FXML private TextField blueField;
//add for all column
    @FXML  private TableColumn termcolumn,ballcolumn01,ballcolumn02,ballcolumn03,ballcolumn04,
            ballcolumn05,ballcolumn06,ballcolumn07,ballcolumn08,
            ballcolumn09,ballcolumn10,ballcolumn11,ballcolumn12,
            ballcolumn13,ballcolumn14,ballcolumn15,ballcolumn16,
            ballcolumn17,ballcolumn18,ballcolumn19,ballcolumn20,
            ballcolumn21,ballcolumn22,ballcolumn23,ballcolumn24,
            ballcolumn25,ballcolumn26,ballcolumn27,ballcolumn28,
            ballcolumn29,ballcolumn30,ballcolumn31,ballcolumn32,
            ballcolumn33,bluecolumn;
    /**
     * Initializes the controller class.
     */
     String[] t_value;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
       BonusLogger.getInstance().log("call DoubleBallController initialize "+url);
       
       checkAssert();
       adjustUISurface();
   handleSearch(null);
   
    }    
    
    @FXML
    public void addForcasting(ActionEvent event)
    {
        UnionLottoSync.datalist.add(new ChinaDoubleBallBean(termField.getText(),
            dateField.getText(),
           str2int(red1Field.getText()),
            str2int(red2Field.getText()),
            str2int(red3Field.getText()),
            str2int(red4Field.getText()),
            str2int(red5Field.getText()),
            str2int(red6Field.getText()),
            str2int(blueField.getText())    
        ));
        
        termField.setText("");
        dateField.setText("");
        red1Field.setText("");          
        red2Field.setText("");
        red3Field.setText("");
        red4Field.setText("");
        red5Field.setText("");
        red6Field.setText("");
        blueField.setText("");
        System.out.println("now size:"+UnionLottoSync.datalist.size());
        tableView.getSelectionModel().select(UnionLottoSync.datalist.size());
    }
 public void checkAssert()
 {
    assert maingridpane == null : MessageUtils.getFormatMessage("assert_msg", "maingridpane");
     assert tableView == null : MessageUtils.getFormatMessage("assert_msg", "tableView");     
     assert content_region == null : MessageUtils.getFormatMessage("assert_msg", "content_region"); 
    assert new_record_region == null : MessageUtils.getFormatMessage("assert_msg", "new_record_region");      

 } 
  private void adjustUISurface()
     {
       BonusLogger.getInstance().log("call adjustUISurface....");
       //get menubar/statusbar height 
     }
 public void modifyGridPane(double width,double height)
 {
BonusLogger.getInstance().log("modifyGridPane width:"+width+",height:"+height);
 maingridpane.setPrefWidth(width);
 maingridpane.setPrefHeight(height);
 tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
 tableView.setPrefWidth(width);
 tableView.setPrefHeight(height);
 tableView.setMinWidth(width);
 tableView.setMinHeight(height);
 
//change column average width
double average = (width-(DBContant.TERM_WIDTH+DBContant.BLUE_WIDTH))/33;

setColumnWidth(termcolumn,DBContant.TERM_WIDTH,new int[]{(int)Math.round(DBContant.TERM_WIDTH/7-0.5)});

setColumnWidth(ballcolumn01,average);
setColumnWidth(ballcolumn02,average);
setColumnWidth(ballcolumn03,average);
setColumnWidth(ballcolumn04,average);
setColumnWidth(ballcolumn05,average);
setColumnWidth(ballcolumn06,average);
setColumnWidth(ballcolumn07,average);
setColumnWidth(ballcolumn08,average);
setColumnWidth(ballcolumn09,average);
//2
setColumnWidth(ballcolumn10,average);
setColumnWidth(ballcolumn11,average);
setColumnWidth(ballcolumn12,average);
setColumnWidth(ballcolumn13,average);
setColumnWidth(ballcolumn14,average);
setColumnWidth(ballcolumn15,average);
setColumnWidth(ballcolumn16,average);
setColumnWidth(ballcolumn17,average);
setColumnWidth(ballcolumn18,average);
setColumnWidth(ballcolumn19,average);
//3
setColumnWidth(ballcolumn20,average);
setColumnWidth(ballcolumn21,average);
setColumnWidth(ballcolumn22,average);
setColumnWidth(ballcolumn23,average);
setColumnWidth(ballcolumn24,average);
setColumnWidth(ballcolumn25,average);
setColumnWidth(ballcolumn26,average);
setColumnWidth(ballcolumn27,average);
setColumnWidth(ballcolumn28,average);
setColumnWidth(ballcolumn29,average);
//4
setColumnWidth(ballcolumn30,average);
setColumnWidth(ballcolumn31,average);
setColumnWidth(ballcolumn32,average);
setColumnWidth(ballcolumn33,average);
setColumnWidth(bluecolumn,DBContant.BLUE_WIDTH,new int[]{(int)Math.round(DBContant.BLUE_WIDTH/4-0.5)});
//
setColumnWidth2(termField,90);
setColumnWidth2(dateField,90);
setColumnWidth2(red1Field,60);
setColumnWidth2(red2Field,60);
setColumnWidth2(red3Field,60);
setColumnWidth2(red4Field,60);
setColumnWidth2(red5Field,60);
setColumnWidth2(red6Field,60);
setColumnWidth2(blueField,60);
//add slider
ftermsld.valueProperty().addListener(new ChangeListener<Number>() {
            
            public void changed(ObservableValue<? extends Number> ov,
                Number old_val, Number new_val) {
                    ftermnum.setText(String.format("%02d", new_val.intValue()));
            }
        });
ntermsld.valueProperty().addListener(new ChangeListener<Number>() {
            
            public void changed(ObservableValue<? extends Number> ov,
                Number old_val, Number new_val) {
                    ntermnum.setText(String.format("%02d", new_val.intValue()));
            }
        });
 }
 private void setColumnWidth(TableColumn col,double width,int...fontwidth)
 {
  col.setPrefWidth(Math.round(width-0.5));
  col.setMinWidth(Math.round(width-0.5));
 col.setResizable(true);
 int finalfont=0;
    if(fontwidth.length>0)
    {
    col.setStyle("-fx-font-size:"+fontwidth[0]+"px;");
    }else
    {
    finalfont = (int)Math.abs(width/2.5-0.5);    
    col.setStyle("-fx-font-size:"+finalfont+"px;");    
    }
 }
  private void setColumnWidth2(TextField col,double width)
 {
  col.setPrefWidth(width);
  col.setMinWidth(width);
// col.setMaxWidth(width);    
 }
 
 boolean filterByTerm(ChinaDoubleBallBean ballbean,String newValue)
 {
  if (newValue == null || newValue.isEmpty()) {
                    return true;
                }
                // Compare first name and last name of every person with filter text.
                String lowerCaseFilter = newValue.toLowerCase();

                if (ballbean.getTerm().toLowerCase().startsWith(lowerCaseFilter) ) {
                    return true; // Filter matches term.
                }else
                {
                return false;    
                }
               
 }
 /**
  * if value is null,no filter work
  * @param ballbean
  * @param value
  * @return 
  */
boolean filterbyRedBall(ChinaDoubleBallBean ballbean,String value)
{
    boolean result=false;
    
                if (value == null || value.trim().isEmpty()) {
                    return true;
                }
                
           t_value=Toolkit.splitStr(value);
                for(String t:t_value)
                 {
                 //System.out.println(t);    
                if(!Toolkit.isNumeric(t))return false;
                 }

                if (ballbean.contains(t_value) ) 
                {
                    return true; // Filter matches term.
                }     
    return result;
}
/**
 * if value is null,no filter work
 * @param ballbean
 * @param value
 * @return 
 */
boolean filterbyBlueBall(ChinaDoubleBallBean ballbean,String value)
{
    boolean result=false;
                if (value == null || value.trim().isEmpty()) {
                    return true;
                }
               if (Integer.valueOf(ballbean.getBlue()).equals(Integer.valueOf(value)) ) 
                {
                    return true; // Filter matches blue ball.
                }     
    return result;
}

boolean latestmatched =false;
int fnum=0;//former history number
int nnum=0;//next number 
long listindex=0;
long latestmatchindex=0;
 int former=0;
 
  @FXML
    public void handleSearch(ActionEvent event)
    {
    System.out.println("hander search...");    
    String redballs=redballfilterField.getText();
    String blueball=blueballfilterField.getText();
    String  termV=this.filterField.getText();
    System.out.println("redballs:"+redballs+" blueball:"+blueball+" term:"+termV);
    if(event!=null)
    {
        globalconfig.filterData.setPredicate(unionlotto -> {
            listindex++;//may be track,perfect
    //clear flag
            unionlotto.setIsnext(false);
        if(latestmatched && 
                noptional.isSelected())//check next record
        {
       if( nnum< Integer.parseInt(ntermnum.getText()))
               {
              nnum++; 
              unionlotto.setIsnext(true);//yes this next term data
              return true;
               }
        latestmatched=false;
        nnum=0;
        }else
        {
         latestmatched=false;   
        }
       //find form record?
        if( foptional.isSelected() && !latestmatched)//skip first line
        {
         former= Integer.parseInt(ftermnum.getText());
         if((former+listindex)<globalconfig.filterData.getSource().size())
         {
//         System.out.println(listindex+"judget ........begin..........."+former);    
           for(int i=0;i<former;i++)
           {
           if(findmatch(globalconfig.filterData.getSource().get((int)listindex+i),termV,blueball,redballs))
           {
              return true;                  
            }
           }
         }
        }
        //find former over
        boolean matched=findmatch(unionlotto,termV,blueball,redballs);
                if(matched)
                {
                latestmatched=true;
                former=0;//must be clear.
                latestmatchindex=listindex;
                return true;
                }else
                {
               latestmatched=false;     
                }
   
      return false;
        
            });
    }
//         sortedData = new SortedList<>(filteredData);
//        sortedData.comparatorProperty().bind(tableView.comparatorProperty());  

 tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
  tableView.setItems(globalconfig.filterData); 
System.out.println("find match filter is:"+globalconfig.filterData.size());
    }
   public int str2int(String str)
   {
    int result=0;
     try
     {
     result=Integer.valueOf(str);
     }catch(Exception e){System.out.println(e.getMessage());}
    return result;
   }
public boolean findmatch(ChinaDoubleBallBean uinonlotto,String termV,String blueball,String  redballs )   
{
  boolean result=false;
        
                 boolean hasterm=true;
                 boolean hasblue=true;
                 boolean hasred=true;  
    //check term
                 if(filterByTerm(uinonlotto,termV))
                 {
                  hasterm=true;   
                 }else
                 {
                   hasterm=false;
                 }
                 //check blue
                  if(filterbyBlueBall(uinonlotto,blueball))
                 {
                  hasblue=true;   
                 }else
                 {
                   hasblue=false;
                 }      
                 //check redball
                if(filterbyRedBall(uinonlotto,redballs))
                 {
                     hasred= true;
                 }else
                {
                    hasred=false;
                }
  result = (hasterm && hasblue && hasred);
  return result;
}
public void analystBI(ActionEvent action)
{
 if(globalconfig.filterData==null || globalconfig.filterData.size()==0)   
 {
  globalconfig.updateSystemStatusBar("没有数据无法分析，请输入过滤条件");
  return;
 }
 UnionLottoBI bnion = new UnionLottoBI();
 bnion.showme();
  System.out.println("button is click")  ;
}
}

